import { doLogin, doQrlogin } from "@/api/passport";
import { getInfo } from "@/api/ucenter/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { MessageBox, Message } from "element-ui";
import websocket from "@/utils/socket";

const getDefaultState = () => {
    return {
        token: getToken(),
        realname: "",
        avatar: ""
    };
};

const state = getDefaultState();

const mutations = {
    RESET_STATE: state => {
        localStorage.clear();
        Object.assign(state, getDefaultState());
    },
    SET_TOKEN: (state, token) => {
        state.token = token;
    },
    SET_NAME: (state, realname) => {
        state.realname = realname;
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar;
    }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, verify, uuid } = userInfo;
    return new Promise((resolve, reject) => {
      doLogin({
        username: username.trim(),
        password: password,
        verify: verify,
        uuid: uuid,
      })
        .then((response) => {
          if (response.code == 200) {
            const { data } = response;
            commit("SET_TOKEN", data.token);
            setToken(data.token);

            let btnRules = data.rules;
            localStorage.setItem("btnRules", btnRules);

            resolve();
          } else {
            Message({
              message: response.msg,
              type: "error",
              duration: 5 * 1000,
            });
            reject(error);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  qrlogin({ commit }, params) {
    const { code } = params;
    return new Promise((resolve, reject) => {
      doQrlogin({
        code: code,
      })
        .then((response) => {
          if (response.code == 200) {
            const { data } = response;
            commit("SET_TOKEN", data.token);
            setToken(data.token);

            let btnRules = data.rules;
            localStorage.setItem("btnRules", btnRules);

            resolve();
          } else {
            Message({
              message: response.msg,
              type: "error",
              duration: 5 * 1000,
            });
            reject(error);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const user = response.data.user;
          if (!user) {
            return reject("验证失败，请重新登录");
          }

          const { realname, avatar } = user;
          websocket.init();
          commit("SET_NAME", realname);
          commit("SET_AVATAR", avatar);
          resolve(user);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  resetAvatar({ commit }, avatar) {
    return new Promise((resolve) => {
      commit("SET_AVATAR", avatar);
      resolve();
    });
  },

  // user logout
  logout({ commit, state }) {
    removeToken(); // must remove  token  first
    resetRouter();
    commit("RESET_STATE");
    websocket.close();
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
};